import type { ChatResponse } from '../types/chat'

// 模拟AI回复数据
const mockResponses = [
  "Hello! I'm your AI Art Assistant, ready to help you create stunning images! I specialize in prompt writing, style selection, and technique optimization. What amazing artwork would you like to create today?",
  "Excellent question! Let me share some pro tips to help you achieve better AI art results:",
  "I love that creative concept! Here are some specific ways to enhance your prompt for more accurate results:",
  "For that type of image, I recommend these proven techniques that work really well:",
  "Let me help you craft a more effective prompt. Here's how to structure it for better results:",
  "Here are some style variations and techniques you should definitely experiment with:",
  "I can definitely help you troubleshoot that! Let's try these proven solutions:",
  "Based on your creative vision, here's my expert approach to achieve the best results:"
]

// 图片生成相关的回复
const imageGenerationResponses = [
  "Perfect! Let's craft an amazing prompt for your image. What's your main subject? (e.g., a mystical forest, cyberpunk cityscape, or fantasy character)",
  "Great choice! For that style, I recommend adding these elements to your prompt: lighting details, composition, and artistic techniques.",
  "To get the best results, try including these key elements in your prompt:\n• Specific lighting (golden hour, dramatic shadows)\n• Art style (photorealistic, digital art, oil painting)\n• Mood and atmosphere (serene, energetic, mysterious)\n• Technical details (high resolution, detailed, professional)",
  "Here are some popular prompt structures that work well:\n• \"A [subject] in [style], [lighting], [mood], [technical specs]\"\n• \"[Art style] of [subject], [composition], [colors], [atmosphere]\"\n• \"[Detailed description], [artistic technique], [quality modifiers]\""
]

// 技术支持相关的回复
const technicalSupportResponses = [
  "I'm here to help with any AI art generation issues! What specific problem are you experiencing?",
  "Let me help you troubleshoot these common AI art issues:\n• Blurry or low-quality results\n• Unexpected style outputs\n• Prompt not working as expected\n• Image-to-image transformation problems",
  "For better results, try these optimization tips:\n1. Use more specific and detailed prompts\n2. Experiment with different style keywords\n3. Adjust quality and detail modifiers\n4. Try different aspect ratios or compositions"
]

class ChatService {
  private n8nWebhookUrl: string
  private textToImageWebhookUrl: string

  constructor() {
    const isDev = import.meta.env.DEV
    const baseUrl = isDev ? '/wkfapi' : 'https://pixeljet-n8n.com'
    this.n8nWebhookUrl = `${baseUrl}/webhook/1d5d76aa-895e-49f9-84ff-f3b6120040e4/chat`
    this.textToImageWebhookUrl = `${baseUrl}/webhook/0181dfaf-165d-4d1e-abab-aa845ede784e`
  }

  // 发送消息到AI服务
  async sendMessage(message: string, onChunk?: (chunk: string) => void, signal?: AbortSignal, enableImageGeneration: boolean = false): Promise<ChatResponse> {
    try {
      // 如果启用了图片生成，先调用文生图API
      if (enableImageGeneration) {
        return await this.sendMessageWithImageGeneration(message, onChunk, signal)
      }
      
      // 只使用N8N webhook
      return await this.callN8nWebhook(message, onChunk, signal)
    } catch (error: any) {
      console.error('N8N webhook error:', error)
      // 如果n8n失败，返回模拟回复
      return this.getMockResponse(message)
    }
  }

  // 发送消息并生成图片
  async sendMessageWithImageGeneration(message: string, onChunk?: (chunk: string) => void, signal?: AbortSignal): Promise<ChatResponse> {
    try {
      // 只调用文生图API，不进行任何聊天处理
      const imageResult = await this.generateImage(message)
      
      if (imageResult.image_url) {
        // 构建包含图片的JSON响应
        const imageResponse = {
          prompt: message,
          image_url: imageResult.image_url
        }
        
        // 如果有流式回调，只发送图片数据，不显示JSON
        if (onChunk) {
          onChunk(JSON.stringify(imageResponse, null, 2))
        }
        
        return {
          success: true,
          message: JSON.stringify(imageResponse, null, 2),
          timestamp: Date.now()
        }
      } else {
        // 如果图片生成失败，返回错误信息
        const errorMessage = '抱歉，图片生成失败，请尝试更详细的描述。'
        if (onChunk) {
          onChunk(errorMessage)
        }
        return {
          success: false,
          message: errorMessage,
          timestamp: Date.now()
        }
      }
    } catch (error: any) {
      console.error('Image generation error:', error)
      // 图片生成失败，返回错误信息，不回退到聊天
      const errorMessage = '抱歉，图片生成过程中出现错误，请稍后重试。'
      if (onChunk) {
        onChunk(errorMessage)
      }
      return {
        success: false,
        message: errorMessage,
        timestamp: Date.now()
      }
    }
  }

  // 生成图片
  async generateImage(prompt: string): Promise<{ image_url: string }> {
    const requestBody = {
      userId: this.getUserId(),
      workId: this.generateWorkId(),
      prompt: prompt.trim(),
      shared: 0,
      anonymous: 0
    }
    
    console.log('Calling text-to-image webhook with:', requestBody)
    
    const response = await fetch(this.textToImageWebhookUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestBody)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    console.log('Text-to-image webhook response:', result)
    
    if (result.image_url) {
      return { image_url: result.image_url }
    } else {
      throw new Error('No image_url in response')
    }
  }

  // 生成用户ID
  private getUserId(): string {
    let userId = localStorage.getItem('userId')
    if (!userId) {
      userId = Math.random().toString(36).substr(2, 9)
      localStorage.setItem('userId', userId)
    }
    return userId
  }

  // 生成工作ID
  private generateWorkId(): string {
    return Math.random().toString(36).substr(2, 9)
  }

  // 获取N8N服务状态
  async getServiceStatus(): Promise<{ n8n: boolean }> {
    try {
      const n8nResponse = await fetch(this.n8nWebhookUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ 
          action: 'sendMessage',
          sessionId: this.generateSessionId(),
          chatInput: 'test' 
        })
      })
      return { n8n: n8nResponse.ok }
    } catch (e) {
      return { n8n: false }
    }
  }

  // 获取模拟回复
  private getMockResponse(message: string): ChatResponse {
    const startTime = Date.now()
    
    // 根据消息内容选择合适的回复
    let response = this.selectResponse(message)
    
    // 模拟网络延迟
    const delay = Math.random() * 1000 + 500
    const processingTime = Date.now() - startTime + delay

    return {
      message: response,
      metadata: {
        model: 'mock-gpt-3.5-turbo',
        tokens: Math.floor(message.length * 1.5),
        processingTime: processingTime
      }
    }
  }

  // 根据消息内容选择合适的回复
  private selectResponse(message: string): string {
    const lowerMessage = message.toLowerCase()
    
    // Image generation related
    if (lowerMessage.includes('image') || lowerMessage.includes('generate') || lowerMessage.includes('create') || lowerMessage.includes('draw') || lowerMessage.includes('picture')) {
      return this.getRandomResponse(imageGenerationResponses)
    }
    
    // Technical support related
    if (lowerMessage.includes('problem') || lowerMessage.includes('error') || lowerMessage.includes('help') || lowerMessage.includes('issue') || lowerMessage.includes('trouble')) {
      return this.getRandomResponse(technicalSupportResponses)
    }
    
    // Greetings
    if (lowerMessage.includes('hi') || lowerMessage.includes('hello') || lowerMessage.includes('hey')) {
      return "Hello! I'm your AI Art Assistant, ready to help you create amazing images! I specialize in prompt writing, style selection, and technique optimization. What amazing artwork would you like to create today?"
    }
    
    // 默认回复
    return this.getRandomResponse(mockResponses)
  }

  // 获取随机回复
  private getRandomResponse(responses: string[]): string {
    return responses[Math.floor(Math.random() * responses.length)]
  }

  // 调用N8N Webhook
  private async callN8nWebhook(message: string, onChunk?: (chunk: string) => void, signal?: AbortSignal): Promise<ChatResponse> {
    const startTime = Date.now()
    
    console.log('发送消息到N8N:', message)
    console.log('是否有流式回调:', !!onChunk)
    
    try {
      const response = await fetch(this.n8nWebhookUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          action: 'sendMessage',
          sessionId: this.generateSessionId(),
          chatInput: message
        }),
        signal
      })

      if (!response.ok) {
        throw new Error(`N8N webhook请求失败: ${response.status}`)
      }

      // 检查是否是流式响应
      const contentType = response.headers.get('content-type')
      console.log('N8N响应Content-Type:', contentType)
      
      // 如果有onChunk回调，优先尝试流式处理
      if (onChunk) {
        try {
          return await this.handleN8nStreamResponse(response, onChunk, startTime, signal)
        } catch (streamError) {
          console.log('流式处理失败，尝试普通JSON处理:', streamError)
          // 如果流式处理失败，回退到普通JSON处理
          try {
            const data = await response.json()
            const processingTime = Date.now() - startTime

            return {
              message: data.message || data.response || data.text || 'Received response',
              metadata: {
                model: 'n8n-webhook',
                tokens: data.tokens || 0,
                processingTime: processingTime
              }
            }
          } catch (jsonError) {
            console.error('JSON解析也失败:', jsonError)
            throw new Error('无法解析N8N响应')
          }
        }
      }

      // 没有onChunk回调，直接处理普通JSON响应
      const data = await response.json()
      const processingTime = Date.now() - startTime

      return {
        message: data.message || data.response || data.text || 'Received response',
        metadata: {
          model: 'n8n-webhook',
          tokens: data.tokens || 0,
          processingTime: processingTime
        }
      }
    } catch (error: any) {
      console.error('N8N webhook调用失败:', error)
      throw new Error('N8N服务暂时不可用，请稍后再试')
    }
  }

  // 处理N8N流式响应
  private async handleN8nStreamResponse(response: Response, onChunk: (chunk: string) => void, startTime: number, signal?: AbortSignal): Promise<ChatResponse> {
    if (!response.body) {
      throw new Error('N8N响应没有body')
    }
    
    const reader = response.body.getReader()
    if (!reader) {
      throw new Error('无法读取N8N响应流')
    }

    const decoder = new TextDecoder()
    let fullMessage = ''
    let buffer = ''

    try {
      while (true) {
        // 检查是否被取消
        if (signal?.aborted) {
          throw new Error('Request aborted')
        }
        
        const { done, value } = await reader.read()
        if (done) break

        const chunk = decoder.decode(value, { stream: true })
        buffer += chunk

        // 处理完整的JSON对象
        const lines = buffer.split('\n')
        buffer = lines.pop() || '' // 保留最后一个可能不完整的行

        for (const line of lines) {
          if (line.trim()) {
            try {
              const data = JSON.parse(line)
              console.log('N8N流式数据:', data)
              
              // 处理N8N的流式数据格式
              if (data.type === 'item' && data.content) {
                console.log('处理流式内容:', data.content)
                fullMessage += data.content
                onChunk?.(data.content)
              } else if (data.type === 'begin') {
                // 开始流式输出
                console.log('N8N流式输出开始')
              } else if (data.type === 'end') {
                // 流式输出结束
                console.log('N8N流式输出结束')
              } else if (data.type === 'error') {
                // 处理错误
                console.error('N8N流式输出错误:', data.content)
                throw new Error(data.content || 'N8N流式输出错误')
              } else if (data.message || data.response || data.text) {
                // 处理其他格式的响应
                const content = data.message || data.response || data.text
                console.log('处理其他格式内容:', content)
                fullMessage += content
                onChunk?.(content)
              }
            } catch (e) {
              console.log('JSON解析失败，作为文本处理:', line, e)
              // 如果不是JSON，直接作为文本处理
              if (line.trim()) {
                fullMessage += line
                onChunk?.(line)
              }
            }
          }
        }
      }

      // 处理剩余的buffer
      if (buffer.trim()) {
        try {
          const data = JSON.parse(buffer)
          if (data.type === 'item' && data.content) {
            fullMessage += data.content
            onChunk?.(data.content)
          }
        } catch (e) {
          if (buffer.trim()) {
            fullMessage += buffer
            onChunk?.(buffer)
          }
        }
      }
    } finally {
      reader.releaseLock()
    }

    const processingTime = Date.now() - startTime

    return {
      message: fullMessage,
      metadata: {
        model: 'n8n-webhook-stream',
        tokens: Math.floor(fullMessage.length * 1.3),
        processingTime: processingTime
      }
    }
  }

  // 生成会话ID
  private generateSessionId(): string {
    return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
  }


  // 获取聊天历史
  async getHistory(): Promise<any[]> {
    try {
      const response = await fetch('/api/chat/history', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      })

      if (!response.ok) {
        throw new Error('获取历史记录失败')
      }

      return await response.json()
    } catch (error) {
      console.error('获取聊天历史失败:', error)
      return []
    }
  }

  // 清空聊天历史
  async clearHistory(): Promise<void> {
    try {
      await fetch('/api/chat/history', {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        }
      })
    } catch (error) {
      console.error('清空聊天历史失败:', error)
    }
  }

  // 检查服务状态
  async checkStatus(): Promise<boolean> {
    try {
      const response = await fetch('/api/chat/status', {
        method: 'GET'
      })
      return response.ok
    } catch (error) {
      console.error('检查服务状态失败:', error)
      return false
    }
  }
}

// 导出单例实例
export const chatService = new ChatService()
